package com.itlong.cloud.controller.old;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.app.old.AppOldUserInfoDto;
import com.itlong.cloud.POJO.VO.app.old.AppOldUserInfoVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.APPDeviceTypeEnum;
import com.itlong.cloud.enumerate.AppUserGenderEnum;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.oldapp.Code;
import com.itlong.cloud.enumerate.oldapp.Message;
import com.itlong.cloud.enumerate.oldapp.MessageDefine;
import com.itlong.cloud.iottp.IIotTpSmsServiceClient;
import com.itlong.cloud.project.app.IAppOldProjectServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppOldRegisterServiceClient;
import com.itlong.cloud.utils.encrypt.Md5;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.picture.VerifyCodeUtils;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.random.RandomUtil;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * <desc>
 *     旧版APP登录与注册版块控制器
 * </desc>
 *
 * Created 2017/10/11
 */
@RestController
@RequestMapping("/mobile/interface")
public class AppOldRegisterController {
    private static final Logger LOG = LoggerFactory.getLogger(AppOldRegisterController.class);

    @Value("${" + PlatformConstants.APP_USER_TOKEN_KEY + "}")
    public String APP_USER_TOKEN_KEY;

    @Autowired
    RedisService redisService;

    @Autowired
    IIotTpSmsServiceClient iIotTpSmsServiceClient;

    @Autowired
    IAppOldRegisterServiceClient iAppOldRegisterServiceClient;

    @Autowired
    IAppOldProjectServiceClient iAppOldProjectServiceClient;

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;

    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;

    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;

    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;

    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    public static  int w = 200, h = 80;

    /**
     * <desc>
     *     旧版APP_获取加密验证串及验证码图片
     * </desc>
     * @param type 1-注册，2-忘记密码，3-更换手机号
     * @return
     * @throws Exception
     */
    @RequestMapping(path = "/app/sign/getSign")
    @ResponseBody
    public Message getSign(String type) throws Exception{
        Message message = null;
        if (StringUtils.isBlank(type)||!(MessageDefine.REGESTER_TYPE.equals(type.trim())||MessageDefine.REPLACE_PHONE_TYPE.equals(type.trim())||MessageDefine.FORGET_PSWD_TYPE.equals(type.trim()))){
            message = new Message(Code.PARAM_ERR);
        }else {
            JSONObject js = new JSONObject();
            try {
                String businessId = LogicIdUtil.bussinessId();
                Integer head = Integer.parseInt(businessId.substring(0,1));
                Integer tail = Integer.parseInt(businessId.substring(businessId.length()-1));
                int position = (head+tail)%businessId.length();
                String sign = businessId.substring(0,position)+type+businessId.substring(position);
                js.put("sign",businessId);
                boolean signflag = redisService.set(sign,RedisConstant.OLD_APP_SIGN_TIME,sign);

                String verifyCode = RandomUtil.getRandomStringByLength(4);
                VerifyCodeUtils verifyCodeUtils = new VerifyCodeUtils();
                //文件后缀
                String fileSuffix = "png";
                UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                        FILE_FTP_HOST,
                        FILE_FTP_USERNAME,
                        FILE_FTP_PASSWORD,
                        FILE_FTP_PORT,
                        verifyCodeUtils.outputImage(w,h,verifyCode),
                        fileSuffix,
                        FILE_ACCESS_URL,
                        FileCatalogEnum.VERIFY_CODE_FILE.getType()
                );
                String verifyCodeUrl = verifyCodeUtils.produceVerifyCodeImg(uploadFileUtil);
                //TODO  旧版APP需要更新版本兼容图片-相对地址（旧）与全地址（新）
                if (StringUtils.isBlank(verifyCodeUrl)){
                    LOG.info("【旧版APP_登录注册版块】生成图片验证码失败");
                    message = new Message(Code.ERROR);
                }else if (StringUtils.isNotBlank(verifyCodeUrl)&&signflag){
                    boolean flag =  redisService.set(verifyCode+sign,RedisConstant.OLD_APP_VERIFY_CODE_TIME,verifyCode);
                    if (flag){
                        String verifyCodechild = verifyCodeUrl.substring(verifyCodeUrl.indexOf("//")+2,verifyCodeUrl.length());

                        verifyCodeUrl = verifyCodechild.substring(verifyCodechild.indexOf("/"),verifyCodechild.length());
                        js.put("verifyCodeImg",verifyCodeUrl);
                        message = new Message(Code.SUCCESS,js);
                    }else {
                        LOG.info("【旧版APP_登录注册版块】生成图片验证码-verifyCode缓存失败");
                        message = new Message(Code.ERROR);
                    }
                }else {
                    LOG.info("【旧版APP_登录注册版块】生成图片验证码-sign缓存失败,verifyCode:"+verifyCode+"--"+sign);
                    message =new Message(Code.ERROR);
                }
            }catch (Exception e){
                throw new DataAccessException("【旧版APP_登录注册版块】生成图片验证码--异常",e);
            }
        }
        return  message;
    }

    /**
     * <desc>
     *     旧版APP_验证加密验证串
     * </desc>
     * @param sign 加签串
     * @param verifyCode  验证码
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(path = "/app/sign/checkVerifyCode")
    public Message checkVerifyCode(String sign,String verifyCode,HttpServletRequest request) throws Exception{
        return new Message(Code.SUCCESS);
    }

    /**
     * <desc>
     *     旧版APP_发送短信
     * </desc>
     * @param phoneNo
     * @param type 类型：1-注册，2-忘记密码，3-更换手机
     * @param sign
     * @param verifyCode
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(path = "/app/msg/sendMsg")
    public Message appSendMessage(String phoneNo,String type,String sign,String verifyCode,HttpServletRequest request) throws Exception{
        if(type.equals("1")||type.equals("3")){
            return new Message(Code.APP_UPDATE);
        }
        String ip = HttpProtocolUtil.getIpAddr(request);
        if (StringUtils.isEmpty(sign)||null==sign||"null".equals(sign)) {
            return new Message(Code.UPDATE_VERSION_REMIND);
        }
        if (sign.length()<18) {
            return new Message(Code.UPDATE_VERSION_REMIND);
        }
        String cacheSign = redisService.get(sign);
        if (StringUtils.isEmpty(cacheSign)||StringUtils.isEmpty(type)||cacheSign.length()<18) {
            LOG.info("【旧版APP_登录注册版块】发送短信,错误请求--" + type + "--" + phoneNo + "--" + ip);
            return new Message(Code.PARAM_ERR);
        }
        if (StringUtils.isNotEmpty(verifyCode)&&null != verifyCode) {
            verifyCode = verifyCode.toUpperCase();
            String isCheckVerifyCode = redisService.get(verifyCode+sign);
            if (!verifyCode.equals(isCheckVerifyCode)) {
                LOG.info("【旧版APP_登录注册版块】发送短信,越过验证码错误--" + type + "--" + phoneNo + "--" + ip);
                return new Message(Code.PARAM_ERR);
            }
        }

        String randomNum = NumberHandlerUtil.randomNum(6);
        String content = "验证码:"+randomNum;
        String typeName = "";
        //验证手机号码是否存在
        AppOldUserInfoDto appOldUserInfoDto = iAppOldRegisterServiceClient.selectDtoByPhone(phoneNo);
        if(MessageDefine.REGESTER_TYPE.equals(type)||MessageDefine.REPLACE_PHONE_TYPE.equals(type)){//注册,更换手机
            if( appOldUserInfoDto!=null&&MessageDefine.REPLACE_PHONE_TYPE.equals(type)){
                typeName = "更换手机";
                if (StringUtils.isNotEmpty(appOldUserInfoDto.getPswd())) {
                    return new Message(Code.EXIST_PHONENO, Code.EXIST_PHONENO.getMsg());
                }else {
                    return new Message(Code.EXIST_AUTH_PHONENO,Code.EXIST_AUTH_PHONENO.getMsg());
                }
            }else if (appOldUserInfoDto != null&&MessageDefine.REGESTER_TYPE.equals(type)) {
                typeName = "注册";
                if (StringUtils.isNotEmpty(appOldUserInfoDto.getPswd())) {
                    return new Message(Code.EXIST_PHONENO, Code.EXIST_PHONENO.getMsg());
                }
            }
        }else if(MessageDefine.FORGET_PSWD_TYPE.equals(type)){//忘记密码
            typeName = "忘记密码";
            if (appOldUserInfoDto == null){
                return new Message(Code.NOT_FOUNDPHONE);
            }
        }else{
            return new Message(Code.PARAM_ERR);
        }
        redisService.set(RedisConstant.OLD_APP_SEND_MSG_KEY + type + phoneNo,RedisConstant.OLD_APP_SEND_MSG_TIME, randomNum);
        boolean sendFlag = iIotTpSmsServiceClient.sendSmsCodeByPhone(phoneNo,content);
        if (sendFlag){
            return new Message(Code.SUCCESS);
        }else {
            return new Message(Code.ERROR,"验证码发送失败，请联系管理员");
        }
    }

    /**
     * <desc>
     *     旧版APP_注册第一步，提交后获取待选择的项目列表
     * </desc>
     * @param phoneNo
     * @param pswd
     * @param smsCode
     * @param sign
     * @param verifyCode
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(path = "/app/register")
    public Message appRegister(String phoneNo,String pswd,String smsCode,String sign,String verifyCode,HttpServletRequest request) throws Exception{
        return new Message(Code.APP_UPDATE);
    }

    /**
     * <desc>
     *     旧版APP_注册第三步，完善信息提交
     * </desc>
     * @param phoneNo
     * @param pswd
     * @param token
     * @param ownerProjectId
     * @param ownerProjectName
     * @param userName
     * @param nickName
     * @param sex
     * @param birthday
     * @param userMemo
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(path = "/app/registerProjectInfo")
    public Message registerProject(String phoneNo,String pswd,String token,String ownerProjectId,String ownerProjectName,
        String userName,String nickName,String sex,String birthday,String userMemo) throws Exception{
        return new Message(Code.APP_UPDATE);
    }

    /**
     * <desc>
     *     旧版APP_登录
     * </desc>
     * @param phoneNo
     * @param pswd
     * @param loginDevice
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(path = "/app/login")
    public Message appLogin(String phoneNo,String pswd,String loginDevice) throws Exception{
        if (StringUtils.isBlank(phoneNo)||StringUtils.isBlank(pswd)||StringUtils.isBlank(loginDevice)){
            LOG.info("【旧版APP_登录注册版块】登出失败--phoneNo:"+phoneNo+"--pswd:"+pswd+"--loginDevice:"+loginDevice);
            return  new Message(Code.PARAM_ERR);
        }
        if ("iOS".equals(loginDevice)){
            loginDevice = APPDeviceTypeEnum.IOS.getType().toString();
        }else if ("android".equals(loginDevice)){
            loginDevice = APPDeviceTypeEnum.ANDROID.getType().toString();
        }
        AppOldUserInfoVO appOldUserInfoVO = iAppOldRegisterServiceClient.appLogin(phoneNo, Md5EncryptUtil.md5(pswd),loginDevice);
        if (appOldUserInfoVO != null){
            if (appOldUserInfoVO.getUserStatus() != 1){
                return new Message(Code.USER_REFUSE);
            }
            return  new Message(Code.SUCCESS,"登录成功",appOldUserInfoVO);
        }else {
            return  new Message(Code.LOGIN_ERROR);
        }
    }

    /**
     * <desc>
     *     旧版APP_登出
     * </desc>
     * @param phoneNo
     * @param token
     * @return
     */
    @ResponseBody
    @RequestMapping(path = "/app/loginOut")
    public Message appLoginOut(String phoneNo,String token){
        try {
            String userId = UserTokenUtil.tokenDecrypt(token,APP_USER_TOKEN_KEY);
            boolean redisflag = redisService.del(RedisConstant.APP_LOGIN+userId);
            if (redisflag){
                return  new Message(Code.SUCCESS);
            }else {
                LOG.info("【旧版APP_登录注册版块】登出失败");
                return  new Message(Code.ERROR);
            }
        }catch (Exception e){
            throw new DataAccessException("【旧版APP_登录注册版块】退出登录失败",e);
        }
    }


    /**
     * <desc>
     *     旧版APP_忘记密码提交
     * </desc>
     * @param phoneNo
     * @param smsCode
     * @param pswd
     * @param sign
     * @param verifyCode
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(path = "/app/retrievePswd")
    public Message appRetrievePswd(String phoneNo,String smsCode,String pswd,String sign,String verifyCode,HttpServletRequest request) throws Exception{
        if(StringUtils.isBlank(phoneNo)||StringUtils.isBlank(smsCode)||StringUtils.isBlank(pswd)||StringUtils.isBlank(sign)||StringUtils.isBlank(verifyCode)) {
            return new Message(Code.NOT_PARAM);
        }
        String randomNum = redisService.get(RedisConstant.OLD_APP_SEND_MSG_KEY+MessageDefine.FORGET_PSWD_TYPE+phoneNo);
        if(randomNum == null || !randomNum.equals(smsCode)){
            return new Message(Code.SMSCODE_ERR);
        }
        //校验图片验证码
        String ip = HttpProtocolUtil.getIpAddr(request);
        if (StringUtils.isNotEmpty(verifyCode)&&null != verifyCode) {
            verifyCode = verifyCode.toUpperCase();
            String isCheckVerifyCode = redisService.get(verifyCode+sign);
            if (!verifyCode.equals(isCheckVerifyCode)) {
                return new Message(Code.VERIFYCODE_ERR);
            }
        }
        Code code = iAppOldRegisterServiceClient.appRetrievePswd(phoneNo,Md5.En(pswd));
        return new Message(code);
    }

    /**
     * <desc>
     *     旧版APP_修改头像
     * </desc>
     * @param phoneNo
     * @param imageStr
     * @param imageType
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(path = "/app/updatePhoto")
    public Message appUpdatePhoto(String phoneNo,String imageStr,String imageType) throws Exception{
        if(StringUtils.isBlank(phoneNo)||StringUtils.isBlank(imageStr)||StringUtils.isBlank(imageType)) {
            return new Message(Code.NOT_PARAM);
        }
        AppOldUserInfoDto appOldUserInfoDto = (AppOldUserInfoDto)redisService.getObject(RedisConstant.OLD_APP_LOGIN_KEY + phoneNo,AppOldUserInfoDto.class);
        if (appOldUserInfoDto == null){
            appOldUserInfoDto = iAppOldRegisterServiceClient.selectDtoByPhone(phoneNo);
        }
        if (appOldUserInfoDto != null){
            String picUrl = iAppOldRegisterServiceClient.updatePhoto(appOldUserInfoDto.getUserId(),imageStr,imageType);
            if (StringUtils.isNotBlank(picUrl)){
                //更新缓存
                appOldUserInfoDto.setPhotoUrl(picUrl);
                String codechild = picUrl.substring(picUrl.indexOf("//")+2,picUrl.length());

                picUrl = codechild.substring(codechild.indexOf("/"),codechild.length());
                redisService.set(RedisConstant.OLD_APP_USER_VO_KEY + phoneNo,RedisConstant.OLD_APP_LOGIN_TIME,appOldUserInfoDto);
                return new Message(Code.SUCCESS,"上传成功",picUrl);
            }else {
                return new Message(Code.ERROR);
            }
        }else {
            return new Message(Code.TOKEN_ERR);
        }
    }

    /**
     * <desc>
     *     旧版APP_修改密码
     * </desc>
     * @param phoneNo
     * @param oldPswd
     * @param newPswd
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(path = "/app/updatePswd")
    public Message appUpdatePswd(String phoneNo,String oldPswd,String newPswd) throws Exception{
        if(StringUtils.isBlank(phoneNo)) {
            return new Message(Code.ERROR, "手机号不能为空");
        }
        if(StringUtils.isBlank(oldPswd)) {
            return new Message(Code.ERROR, "旧密码不能为空");
        }
        if(StringUtils.isBlank(newPswd)) {
            return new Message(Code.ERROR, "新密码不能为空");
        }
        Code code = iAppOldRegisterServiceClient.appUpdatePswd(phoneNo,Md5.En(oldPswd),Md5.En(newPswd));
        AppOldUserInfoVO appOldUserInfoVO = (AppOldUserInfoVO)redisService.getObject(RedisConstant.OLD_APP_USER_VO_KEY+phoneNo,AppOldUserInfoVO.class);
        return new Message(code,appOldUserInfoVO);
    }

    /**
     * <desc>
     *     旧版APP_修改手机号
     * </desc>
     * @param phoneNo
     * @param loginPswd
     * @param newPhoneNo
     * @param smsCode
     * @param sign
     * @param verifyCode
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(path = "/app/updatePhone")
    public Message appUpdatePhone(String phoneNo,String loginPswd,String newPhoneNo,String smsCode,String sign,String verifyCode,HttpServletRequest request) throws Exception{
        return  new Message(Code.APP_UPDATE);
    }




    /**
     * <desc>
     *     旧版APP_修改昵称
     * </desc>
     * @param phoneNo
     * @param nickName
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(path = "/app/updateNickName")
    public Message appUpdateNickName(String phoneNo,String nickName) throws Exception{
        if(StringUtils.isBlank(phoneNo)||StringUtils.isBlank(nickName)) {
            return new Message(Code.NOT_PARAM);
        }
        Code code = iAppOldRegisterServiceClient.updateNickName(phoneNo,nickName);
        return  new Message(code);
    }

    /**
     * <desc>
     *     旧版APP_修改姓名
     * </desc>
     * @param phoneNo
     * @param userName
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(path = "/app/updateUserName")
    public Message appUpdateUserName(String phoneNo,String userName) throws Exception{
        if(StringUtils.isBlank(phoneNo)||StringUtils.isBlank(userName)) {
            return new Message(Code.NOT_PARAM);
        }
        Code code = iAppOldRegisterServiceClient.appUpdateUserName(phoneNo,userName);
        return  new Message(code);
    }

    /**
     * <desc>
     *     旧版APP_修改性别
     * </desc>
     * @param phoneNo
     * @param sex 性别：0男 1女
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(path = "/app/updateUserSex")
    public Message appUpdateUserSex(String phoneNo, String sex) throws Exception{
        if(StringUtils.isBlank(phoneNo)||StringUtils.isBlank(sex)) {
            return new Message(Code.NOT_PARAM);
        }
        if("先生".equals(sex)||"男".equals(sex)) {
            sex = AppUserGenderEnum.USERINFO_GENDER_MAN.getType().toString();
        } else {
            sex = AppUserGenderEnum.USERINFO_GENDER_WOMAN.getType().toString();
        }
        Code code = iAppOldRegisterServiceClient.updateUserSex(phoneNo, sex);
        return  new Message(code);
    }

    /**
     * <desc>
     *     旧版APP_检查核验用户的token正确性
     * </desc>
     * @param phoneNo
     * @param token
     * @param projectId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(path = "/app/checkUserStatus")
    public Message checkUserStatus(String phoneNo,String token,String projectId) throws Exception{
        if (StringUtils.isEmpty(phoneNo)||StringUtils.isEmpty(projectId)||StringUtils.isEmpty(token)) {
            return new Message(Code.PARAM_ERR);
        }
        Code code = iAppOldRegisterServiceClient.checkUserStatus(phoneNo,token);
        return  new Message(code);
    }







}
